package org.droid.campusorder;

import java.io.File;
import java.util.Hashtable;

import org.droid.R;
import org.droid.campusorder.action.RespGetShopsAction;
import org.droid.campusorder.adapter.CanteenAdapter;
import org.droid.campusorder.adapter.CanteenShopAdapter;
import org.droid.campusorder.bean.RespShopsBean;
import org.droid.campusorder.bean.ShopsBean;
import org.droid.campusorder.common.CommonMethod;
import org.droid.campusorder.common.Config;
import org.droid.campusorder.common.Debug;
import org.droid.campusorder.common.GlobalData;
import org.droid.campusorder.manager.DownManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class CanteenShopActivity extends MyActivity implements CommonMethod {
	private RespGetShopsAction rgsAction;
	private RespShopsBean rsb;;
	private Hashtable<String, String> ht;
	private String[] shopLogoPaths;
	private GridView mGridView;
	private Button btnChange; // 切换食堂
	private ImageButton ibtnAbout; // 关于
	private TextView tv_title;
	// 下列的变量是关于popwindow的
	private View popwinView = null;
	PopupWindow pop;
	int mviewpos[] = new int[2];
	DisplayMetrics metrics;
	int mpaddingLeft = 5;
	// 与在layout文件下new_file.xml中popwindow的宽度对应。都为280px
	int popWidth = 280;
	private CanteenShopAdapter canteenShopAdapter;
	private ShopsAsyncTask shopsAsyncTask;
	private Debug debug;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		debug = new Debug("CanteenShopActivity");
		shopsAsyncTask = new ShopsAsyncTask();
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		setContentView(R.layout.canteen_shop);
		findAllViewById();
		String title = GlobalData.canteenBeanList.get(receivedValue())
				.getName();
		tv_title.setText(title);
		canteenShopAdapter = new CanteenShopAdapter(getApplicationContext());
		mGridView.setAdapter(canteenShopAdapter);
		setListenner();
		reqShop();
	}

	@Override
	protected void onResume() {
		super.onResume();
		changAboutBgHandler.sendEmptyMessage(1);
	}

	@Override
	public void findAllViewById() {
		tv_title = (TextView) findViewById(R.id.tv_cs_title);
		mGridView = (GridView) findViewById(R.id.gv_cs_canteen);
		btnChange = (Button) findViewById(R.id.btn_cs_change);
		ibtnAbout = (ImageButton) findViewById(R.id.ibtn_cs_about);
	}

	@Override
	public void setListenner() {
		mGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 弹出单击的GridView元素的位置
				// Toast.makeText(getApplicationContext(),
				// canteenShopAdapter.getCanteenShopLogoPaths()[position],
				// Toast.LENGTH_SHORT).show();
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(),
						DishesListActivity.class);
				startActivity(intent);
			}
		});

		btnChange.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), "切换食堂",
						Toast.LENGTH_LONG).show();
				mpaddingLeft = 5;
				v.getLocationOnScreen(mviewpos);
				if (!(mviewpos[0] + popWidth < metrics.widthPixels)) {
					// mpaddingLeft = (mviewpos[0] - (metrics.widthPixels -
					// popWidth));
					mpaddingLeft = (metrics.widthPixels - mviewpos[0])
							/ 2
							+ ((mviewpos[0] - (metrics.widthPixels - popWidth)));
				}
				popwinView = getLayoutInflater().inflate(
						R.layout.canteen_shop_popwin, null);
				initPopwinLv();
				initPopwinSingIcon(popwinView, v.getId());
				popMenu(popwinView, v);
			}
		});

		ibtnAbout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changAboutBgHandler.sendEmptyMessage(0);
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), AboutActivity.class);
				startActivity(intent);
			}
		});

	}

	/** 接受MainActivity传来参数 */
	private int receivedValue() {
		Bundle bundle = new Bundle();
		bundle = this.getIntent().getExtras();
		return bundle.getInt("CanteenContentPosition");
	}

	private void popMenu(View popview, View view) {
		if (pop == null) {
			pop = new PopupWindow(popview, LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT, true);
			pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
			pop.setAnimationStyle(R.style.PopupAnimation);
			pop.setOutsideTouchable(true);
			pop.showAsDropDown(view, Gravity.CENTER_HORIZONTAL, 0);
			pop.update();
		} else {
			if (pop.isShowing()) {
				pop.dismiss();
				pop = null;
			} else {
				pop = null;
				pop = new PopupWindow(popview, LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT, true);
				pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
				pop.setAnimationStyle(R.style.PopupAnimation);
				pop.setOutsideTouchable(false);
				pop.showAsDropDown(view, Gravity.CENTER_HORIZONTAL, 0);
				// 更新popwin的状态
				pop.update();
			}
		}
	}

	/** 初始化Popwin中的箭头指示图标 */
	private void initPopwinSingIcon(final View view, int id) {
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				new LayoutParams(LayoutParams.WRAP_CONTENT,
						LayoutParams.WRAP_CONTENT));
		ImageView imageView = new ImageView(this);
		imageView.setImageResource(R.drawable.pop_signicon);
		LinearLayout mLayout = (LinearLayout) view
				.findViewById(R.id.ll_cs_pop_signicon);
		mLayout.addView(imageView, params);
		mLayout.setPadding(mpaddingLeft, 0, 0, 0);
	}

	/** 初始化Popwin中的listview */
	private void initPopwinLv() {
		ListView mlv_cs_pop = (ListView) popwinView
				.findViewById(R.id.lv_cs_pop);
		// Popwin中listview的监听器
		mlv_cs_pop.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int arg2,
					long arg3) {
				String title = GlobalData.canteenBeanList.get(arg2).getName();
				tv_title.setText(title);
				refreshHandler.sendEmptyMessage(0);
				popMenu(popwinView, v);
			}
		});
		CanteenAdapter adapter = new CanteenAdapter(getApplicationContext());
		mlv_cs_pop.setAdapter(adapter);
		adapter = null;
	}

	/** 请求服务器shops信息 */
	private void reqShop() {
		// 用于请求服务器
		rgsAction = new RespGetShopsAction(CanteenShopActivity.this);
		// 添加请求参数
		ht = new Hashtable<String, String>();
		ht.put("forword", "GetShops");
		ht.put("id", "1");
		try {

			rsb = (RespShopsBean) rgsAction.getMsgFromNetwork(null,
					Config.SubConfig.Req, ht);

			ht = null;
			rgsAction = null; // 不用的对象设置为null
		} catch (Exception e) {
			e.printStackTrace();
		}
		debug.debug("shop返回码：" + rsb.getReturnCode());
		if (GlobalData.shopsBeanList != null) {
			GlobalData.shopsBeanList.clear();
		}
		GlobalData.shopsBeanList = rsb.getShopsBeanList();
		setShopLogoSrc();
		canteenShopAdapter.setCanteenShopLogoPaths(shopLogoPaths);
		initShopViewHandler.sendEmptyMessage(0);

		debug.debug(GlobalData.shopsBeanList.size());
		shopsAsyncTask.execute("startdownload");// 里面的值是随便传的
	}

	/** 从SD卡获取商店logo图片存放的地址 */
	private void setShopLogoSrc() {
		int length = GlobalData.shopsBeanList.size();
		shopLogoPaths = new String[length];
		for (int i = 0; i < length; i++) {
			String ShopLogoPath = GlobalData.dirPath
					+ "Shop/"
					+ DownManager.getImageFileName(GlobalData.shopsBeanList
							.get(i).getPic());
			shopLogoPaths[i] = ShopLogoPath;
		}
	}

	private class ShopsAsyncTask extends AsyncTask<String, Integer, Bitmap> {
		@Override
		protected Bitmap doInBackground(String... params) {
			File file;
			for (int i = 0; i < GlobalData.shopsBeanList.size(); i++) {
				ShopsBean sb = GlobalData.shopsBeanList.get(i);
				debug.debug("shop名字：" + sb.getName());
				debug.debug("shopLogo：" + sb.getPic());
				// 设置下载的广告图片的文件名及路径
				String fileDir = GlobalData.dirPath + "Shop/";
				File fileFolder = new File(fileDir);
				if (!fileFolder.exists()) {
					fileFolder.mkdirs();
				}
				String imagePath = fileDir
						+ DownManager.getImageFileName(sb.getPic());
				file = new File(imagePath);
				if (!file.exists()) {// 若文件存在则不下载
					debug.debug("开始下载====================================");
					debug.debug("Strat-->>download file:" + imagePath);
					try {
						DownManager.downImage(sb.getPic(), imagePath);
						publishProgress(i);
					} catch (Exception e) {
						debug.debug(e.getMessage());
						e.printStackTrace();
					}
					debug.debug("download file:" + imagePath);
				}
			}
			return null;
		}

		protected void onProgressUpdate(Integer... progress) {// 在调用publishProgress之后被调用，在ui线程执行
			canteenShopAdapter.notifyDataSetChanged();
		}

		protected void onPostExecute(Bitmap result) {// 后台任务执行完之后被调用，在ui线程执行
			debug.debug("————————————————————————————————over~");

		}

		protected void onPreExecute() {// 在doInBackground(Params...)之前被调用，在ui线程执行
		}

		protected void onCancelled() {// 在ui线程执行
		}
	}

	private Handler changAboutBgHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				ibtnAbout.setBackgroundResource(R.drawable.top_info_pressed);
			} else {
				ibtnAbout.setBackgroundResource(R.drawable.top_info_normal);
			}
		}
	};

	private Handler refreshHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (shopsAsyncTask != null) {
				shopsAsyncTask.cancel(true);
			}
			shopsAsyncTask = new ShopsAsyncTask();
			reqShop();
		}
	};

	public Handler initShopViewHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			canteenShopAdapter.notifyDataSetChanged();
		}
	};
}
